{% extends 'base.html' %}

{% block title %}文本比较工具{% endblock %}

{% block content %}
<div class="container mx-auto px-4 py-8">
    <div class="mb-8">
        <h1 class="text-3xl font-bold text-gray-800 mb-2">文本比较工具</h1>
        <p class="text-gray-600">比较两段文本的差异并高亮显示</p>
    </div>

    <div class="bg-white shadow-md rounded-lg p-6">
        <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6">
            <div>
                <label for="text1" class="block text-sm font-medium text-gray-700 mb-2">文本1</label>
                <textarea id="text1" rows="10" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">{{ text1 or '' }}</textarea>
                <div class="mt-2 flex justify-between text-sm">
                    <span class="text-gray-500">字符数: <span id="char-count-1">0</span></span>
                    <button type="button" id="clear-text1" class="text-blue-600 hover:underline">清空</button>
                </div>
            </div>
            <div>
                <label for="text2" class="block text-sm font-medium text-gray-700 mb-2">文本2</label>
                <textarea id="text2" rows="10" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">{{ text2 or '' }}</textarea>
                <div class="mt-2 flex justify-between text-sm">
                    <span class="text-gray-500">字符数: <span id="char-count-2">0</span></span>
                    <button type="button" id="clear-text2" class="text-blue-600 hover:underline">清空</button>
                </div>
            </div>
        </div>

        <div class="mb-6 flex gap-3">
            <button id="compare-btn" type="button" class="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2">
                <i class="fas fa-exchange-alt mr-2"></i>比较差异
            </button>
            <button id="swap-btn" type="button" class="px-4 py-2 bg-gray-200 text-gray-700 rounded-md hover:bg-gray-300 focus:outline-none focus:ring-2 focus:ring-gray-500 focus:ring-offset-2">
                <i class="fas fa-sync-alt mr-2"></i>交换文本
            </button>
        </div>

        <!-- 加载指示器 -->
        <div id="loading-indicator" class="hidden">
            <div class="flex justify-center items-center my-6">
                <div class="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
                <span class="ml-3 text-gray-600">正在比较...</span>
            </div>
        </div>

        <div id="result-container" class="mt-8 hidden">
            <h2 class="text-xl font-semibold text-gray-800 mb-4">比较结果</h2>
            <div class="bg-gray-50 p-4 rounded-md overflow-x-auto">
                <pre id="diff-result" class="text-sm font-mono whitespace-pre-wrap"></pre>
            </div>
            <div class="mt-4 flex justify-end gap-2">
                <button id="copy-btn" class="px-3 py-1 bg-gray-200 text-gray-700 rounded hover:bg-gray-300 focus:outline-none focus:ring-2 focus:ring-gray-500">
                    <i class="fas fa-copy mr-1"></i>复制结果
                </button>
                <button id="download-btn" class="px-3 py-1 bg-gray-200 text-gray-700 rounded hover:bg-gray-300 focus:outline-none focus:ring-2 focus:ring-gray-500">
                    <i class="fas fa-download mr-1"></i>下载结果
                </button>
            </div>
        </div>
    </div>

    <div class="mt-8 bg-blue-50 rounded-lg p-4">
        <h3 class="text-lg font-medium text-blue-800 mb-2">使用说明</h3>
        <ul class="list-disc pl-5 text-blue-700 space-y-1">
            <li>在左侧输入第一段文本，右侧输入第二段文本</li>
            <li>点击"比较差异"按钮进行对比</li>
            <li>结果中以"-"开头的行表示第一个文本中存在但第二个文本中不存在或不同的内容</li>
            <li>结果中以"+"开头的行表示第二个文本中存在但第一个文本中不存在或不同的内容</li>
            <li>使用"交换文本"按钮可以快速互换两个文本框的内容</li>
        </ul>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // 获取DOM元素
    const text1 = document.getElementById('text1');
    const text2 = document.getElementById('text2');
    const charCount1 = document.getElementById('char-count-1');
    const charCount2 = document.getElementById('char-count-2');
    const clearText1 = document.getElementById('clear-text1');
    const clearText2 = document.getElementById('clear-text2');
    const compareBtn = document.getElementById('compare-btn');
    const swapBtn = document.getElementById('swap-btn');
    const resultContainer = document.getElementById('result-container');
    const diffResult = document.getElementById('diff-result');
    const copyBtn = document.getElementById('copy-btn');
    const downloadBtn = document.getElementById('download-btn');
    const loadingIndicator = document.getElementById('loading-indicator');
    
    // 字符计数函数
    function updateCharCount() {
        charCount1.textContent = text1.value.length;
        charCount2.textContent = text2.value.length;
    }
    
    // 初始化字符计数
    text1.addEventListener('input', updateCharCount);
    text2.addEventListener('input', updateCharCount);
    updateCharCount();
    
    // 清空按钮
    clearText1.addEventListener('click', function() {
        text1.value = '';
        updateCharCount();
    });
    
    clearText2.addEventListener('click', function() {
        text2.value = '';
        updateCharCount();
    });
    
    // 交换文本按钮
    swapBtn.addEventListener('click', function() {
        const temp = text1.value;
        text1.value = text2.value;
        text2.value = temp;
        updateCharCount();
    });
    
    // 比较按钮 - 使用AJAX
    compareBtn.addEventListener('click', function() {
        const value1 = text1.value.trim();
        const value2 = text2.value.trim();
        
        if (!value1 || !value2) {
            showMessage('请在两个文本框中都输入内容', 'error');
            return;
        }
        
        // 显示加载指示器
        loadingIndicator.classList.remove('hidden');
        resultContainer.classList.add('hidden');
        
        // 准备发送的数据
        const formData = new FormData();
        formData.append('text1', value1);
        formData.append('text2', value2);
        
        // 发送AJAX请求
        fetch('{{ url_for("text_tools.text_diff_ajax") }}', {
            method: 'POST',
            body: formData,
            headers: {
                'X-Requested-With': 'XMLHttpRequest'
            }
        })
        .then(response => {
            if (!response.ok) {
                throw new Error('网络请求失败');
            }
            return response.json();
        })
        .then(data => {
            // 隐藏加载指示器
            loadingIndicator.classList.add('hidden');
            
            if (data.error === 0) {
                // 显示结果
                diffResult.textContent = data.result;
                resultContainer.classList.remove('hidden');
                
                // 高亮差异
                highlightDifferences();
                
                if (data.result === '两段文本完全相同') {
                    showMessage('比较完成：两段文本完全相同');
                } else {
                    showMessage('比较完成：发现差异');
                }
            } else {
                showMessage(data.message || '比较失败', 'error');
            }
        })
        .catch(error => {
            // 隐藏加载指示器
            loadingIndicator.classList.add('hidden');
            showMessage('请求出错: ' + error.message, 'error');
        });
    });
    
    // 高亮差异行
    function highlightDifferences() {
        const content = diffResult.textContent;
        const highlightedContent = content
            .replace(/^- .+$/gm, '<span class="text-red-600">$&</span>')
            .replace(/^\+ .+$/gm, '<span class="text-green-600">$&</span>');
        diffResult.innerHTML = highlightedContent;
    }
    
    // 复制按钮
    copyBtn.addEventListener('click', function() {
        const textToCopy = diffResult.textContent;
        
        navigator.clipboard.writeText(textToCopy).then(function() {
            showMessage('已复制到剪贴板');
        }, function() {
            // 备用复制方法
            const textarea = document.createElement('textarea');
            textarea.textContent = textToCopy;
            document.body.appendChild(textarea);
            textarea.select();
            document.execCommand('copy');
            document.body.removeChild(textarea);
            showMessage('已复制到剪贴板');
        });
    });
    
    // 下载按钮
    downloadBtn.addEventListener('click', function() {
        const textToDownload = diffResult.textContent;
        const blob = new Blob([textToDownload], { type: 'text/plain' });
        const url = URL.createObjectURL(blob);
        
        const a = document.createElement('a');
        a.href = url;
        a.download = '文本比较结果.txt';
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(url);
        
        showMessage('文件已下载');
    });
    
    // 显示消息提示
    function showMessage(message, type = 'success') {
        const toast = document.createElement('div');
        
        toast.className = 'fixed bottom-4 right-4 px-4 py-2 rounded shadow-lg z-50 transition-opacity duration-500';
        toast.style.opacity = '0';
        
        if (type === 'error') {
            toast.classList.add('bg-red-500', 'text-white');
        } else {
            toast.classList.add('bg-green-500', 'text-white');
        }
        
        toast.textContent = message;
        
        document.body.appendChild(toast);
        
        // 淡入效果
        setTimeout(() => {
            toast.style.opacity = '1';
        }, 10);
        
        // 3秒后淡出并移除
        setTimeout(() => {
            toast.style.opacity = '0';
            setTimeout(() => {
                document.body.removeChild(toast);
            }, 500);
        }, 3000);
    }
});
</script>
{% endblock %} 